package io.xccit.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.xccit.model.common.result.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2025/6/4
 * <p>自定义BlockException</p>
 */
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       String resourceName,
                       BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        AjaxResult<Object> result = AjaxResult.error("资源:"+ resourceName +"已被限流,原因:" + e.getClass());
        String json = objectMapper.writeValueAsString(result);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
